<template>
  <!--  定义一个容器存放代码编译器-->
  <div id="codeEditor" ref="codeRef" style="min-height: 600px"></div>
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor";
import { onMounted, ref, toRaw, withDefaults, defineProps, watch } from "vue";

//定义组件属性类型;
interface Props {
  value: string;
  language?: string;
  handleChange: (v: string) => void;
}

//给组件指定初始值
const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  language: () => "java",
  handleChange: (v: string) => {
    console.log(v);
  },
});
const codeRef = ref();
const codeEditor = ref();
//监听language的变化
watch(
  () => props.language,
  () => {
    if (codeEditor.value) {
      monaco.editor.setModelLanguage(
        toRaw(codeEditor.value).getModel(),
        props.language
      );
    }
  }
);
onMounted(() => {
  //判断ref是否为空
  if (!codeRef.value) {
    return;
  }
  //创建一个代码编辑器 存放在一个div中
  codeEditor.value = monaco.editor.create(codeRef.value, {
    value: props.value, //编辑器中输入的值
    language: props.language, //语言
    automaticLayout: true,
    colorDecorators: true,
    minimap: {
      //小地图
      enabled: true,
    },
    readOnly: false, //是否开启只读
    theme: "vs-dark", //编辑器的主题
  });

  //监听编辑器内容变化
  codeEditor.value.onDidChangeModelContent(() => {
    props.handleChange(toRaw(codeEditor.value).getValue());
  });
});
</script>
